package repo

import (
	"context"
	"face-revive-task/entity/config"
	"fmt"
	"gorm.io/gorm"
	"time"
)

const (
	Waiting int8 = 1
	Success int8 = 2
	Failed  int8 = 3
)

type RecordPO struct {
	Id   int `gorm:"primaryKey"`
	Uid  int64
	Type int8
	Src  string
	Dst  string
	// 1 待处理；2 成功；3 失败；
	Status     int8
	CreateTime time.Time
	UpdateTime time.Time
}

func (r *RecordPO) TableName() string {
	return "t_record"
}

func getDb() *gorm.DB {
	return config.DbClient.WithContext(context.Background())
}

// QryWaiting 查询待处理的任务
func QryWaiting() ([]*RecordPO, error) {
	var records []*RecordPO
	result := getDb().Where("status = ?", Waiting).Find(&records)
	if result.Error != nil {
		return nil, result.Error
	}
	return records, nil
}

func Update(id int, status int8, dst string) error {
	err := getDb().Transaction(func(tx *gorm.DB) error {
		result := tx.Select("Status", "UpdateTime", "Dst").
			Where("id = ? ", id).Limit(2).Updates(&RecordPO{
			Dst:        dst,
			Status:     status,
			UpdateTime: time.Now(),
		})
		if result.Error != nil {
			return result.Error
		}
		if result.RowsAffected != 1 {
			return fmt.Errorf("RowsAffected %d", result.RowsAffected)
		}
		return nil
	})
	return err
}
